package com.example.statistics.ex

import java.util.regex.Matcher
import java.util.regex.Pattern


// ======正则表达式======
fun String?.isUrl(): Boolean {
    //val pattern = "^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~/])+$";
    val pattern = "http://"
    return match(pattern)
}

fun String?.isEmail(): Boolean {
    val pattern = "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}";
    return match(pattern)
}

fun String.isContainNumber(): Boolean {
    val p = Pattern.compile("[0-9]")
    val m: Matcher = p.matcher(this)
    return m.find()
}

fun String?.isPhone(): Boolean {
    val pattern = "^1[34578]\\d{9}$"
    return match(pattern)
}

fun String?.isNumber(): Boolean {
    if (this.isNullOrBlank()) return false
    val pattern = "^[+-]?[0-9]+(\\.[0-9]+)?([eE][+-]?[0-9]+)?$"
    return match(pattern)
}

fun String.strToFloat(): Float {
    var num = 0f
    if (this.isEmpty()) return num
    val regEx = "([0-9]+.?[0-9]+)|([0-9]+)"
    val p: Pattern = Pattern.compile(regEx)
    val m: Matcher = p.matcher(this)

    if (m.find()) {
        num = m.group(0).orEmpty().trim().toFloat()
    }
    return num
}

fun String.strToInt(): Int {
    val regEx = "([0-9]+.?[0-9]+\$)|([0-9]+)"
    val p: Pattern = Pattern.compile(regEx)
    val m: Matcher = p.matcher(this)
    var num = 0
    if (m.find()) {
        num = m.group(0).orEmpty().trim().toInt()
    }
    return num
}


fun String.phone(): String {
    val regex = "1[3-9][0-9]{9}"
    val p: Pattern = Pattern.compile(regex)
    val m: Matcher = p.matcher(this)
    var phone = ""
    if (m.find()) {
        phone = m.group(0).orEmpty()
    }
    return phone
}

private fun String?.match(pattern: String): Boolean {
    if (this.isNullOrBlank()) {
        return false
    }
    val httpPattern = Pattern.compile(pattern)
    if (httpPattern.matcher(this).matches()) {
        return true
    }
    return false
}
